package com.app.wifi_gps_tethering;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements LocationListener{
	Button btnStart;
	Button btnStop;
	Button btnExit;
	TextView textView;
	MulticastSocket mSocket;
	WifiManager wm; 
	WifiLock lock;
	MulticastLock mcLock;
	Thread thread; 
	Handler myHandler;
	Activity self;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStart = (Button) findViewById(R.id.btnStart);
        btnStop = (Button) findViewById(R.id.btnStop);
        btnExit = (Button) findViewById(R.id.btnExit);
        textView = (TextView) findViewById(R.id.textView1);
        
        wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        myHandler = new Handler();
        self = this;
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	    String mocLocationProvider = LocationManager.GPS_PROVIDER;
	    locationManager.addTestProvider(mocLocationProvider, false, false,
	            false, false, true, false, false, 0, 5);
	    locationManager.setTestProviderEnabled(mocLocationProvider, true);
	    try{
	    	locationManager.requestLocationUpdates(mocLocationProvider, 0, 0, this);
	    }
	    catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    thread = new Thread() {
        	private GeoConvertor geoConvertor = new GeoConvertor();
			
			@SuppressWarnings("null")
			@Override
			public void run() {
		        MulticastLock mcLock = wm.createMulticastLock("mydebuginfo");  
		        mcLock.acquire();  

		        MulticastSocket mSocket = null; 
				try{
					mSocket = new MulticastSocket(1125);
					mSocket.joinGroup(InetAddress.getByName("224.0.1.11"));
				} catch(Exception e)
				{
					e.printStackTrace();
				}
				Location mockLocation = new Location(LocationManager.GPS_PROVIDER);
				while(null != mSocket)
				{
					byte[] buffer = new byte[256];
					DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
					try { 
						mSocket.receive(packet);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					String nmea =  new String(packet.getData(), 0, packet.getLength());
					final String line = nmea;
					myHandler.post(new Runnable(){
						public void run() {
							textView.setText(line);
							
						}
					});
					
					LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
					mockLocation = geoConvertor.ConvertFromNMEA(mockLocation, line);					
					locationManager.setTestProviderLocation(LocationManager.GPS_PROVIDER, mockLocation);
					
					//myHandler.post(this);
				}
				
				try {
					mSocket.leaveGroup(InetAddress.getByName("224.0.1.11"));
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mSocket.close();
				mcLock.release();
				
			}
		};
        
        //Start
        btnStart.setOnClickListener(new OnClickListener() {
            @Override
			public void onClick(View arg0) 
	    		{
	    			StartListen();
	    		}                          
	    	});
        btnStop.setOnClickListener(new OnClickListener() {
            @Override
			public void onClick(View arg0) 
	    		{
            	textView.setText("Stopped!");
            		StopListen();
	    		}                          
	    	});        
        //stop
        btnExit.setOnClickListener(new OnClickListener() {
            @Override
			public void onClick(View arg0) 
            		{
            			Close();
            		}                          
            	});        
    }
    
    public void StartListen()
    {
    	thread.start();
    }
    
    public void StopListen()
    {
    	//thread.SetStop();
    	thread.interrupt();
    }
    
    public void Close()
    {
    	StopListen();
    	android.os.Process.killProcess(android.os.Process.myPid());
    }
@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}    
}
